package com.xiaoma.thread.wait.qiou.first;

/**
 * @author maj
 * @ClassName Test
 * @Description
 * @date 2020-10-17 11:13
 */
public class Test {

  private static int count = 0;
  private static Object lock = new Object();


  public static void main(String[] args) throws InterruptedException {

      Thread even = new Thread(() -> {
        while (count <= 100) {
          synchronized (lock) {
            System.out.println("偶数: " + count++);
            lock.notifyAll();

  /*          for (int i=0;i<10;i++){
              System.out.println(i);
            }*/

            try {
              // 如果还没有结束，则让出当前的锁并休眠
              if (count <= 100) {
                lock.wait();
              }
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        }
      });


      Thread odd = new Thread(() -> {
        while (count <= 100) {
          synchronized (lock) {
            System.out.println("奇数: " + count++);
            lock.notifyAll();
            try {
              // 如果还没有结束，则让出当前的锁并休眠
              if (count <= 100) {
                lock.wait();
              }
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        }
      });


    even.start();
      // 确保偶数线程线先获取到锁
      Thread.sleep(1);
    odd.start();


    }

}
